package io.github.shang11925.sbvuewelearn.service.impl;

import io.github.shang11925.sbvuewelearn.dao.VideoResourcesRepository;
import io.github.shang11925.sbvuewelearn.dto.VideoResourcesDTO;
import io.github.shang11925.sbvuewelearn.entity.VideoResources;
import io.github.shang11925.sbvuewelearn.service.VideoResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class VideoResourcesServiceImpl implements VideoResourcesService {
    @Autowired
    VideoResourcesRepository videoResourceRepository;

    @Value("${custom.upload.base-path}")
    String uploadBasePath;
    @Value("${custom.upload.video-path}")
    String videoResPath;

    @Override
    public void add(VideoResourcesDTO videoResourcesDTO) {
        VideoResources videoResources = new VideoResources();

        videoResources.setVideoId(videoResourcesDTO.getVideoId());
        videoResources.setVideoUrl(videoResourcesDTO.getVideoUrl());
        videoResources.setTitle(videoResourcesDTO.getTitle());
        videoResources.setSectionId(videoResourcesDTO.getSectionId());
        videoResources.setDescription(videoResourcesDTO.getDescription());
        videoResources.setOrderNumber(videoResourcesDTO.getOrderNumber());

        videoResourceRepository.save(videoResources);
    }

    @Override
    public List<VideoResources> findBySectionId(Long sectionId) {
        return videoResourceRepository.findBySectionId(sectionId);
    }

    @Override
    public void uploadCover(MultipartFile file, VideoResourcesDTO videoResourcesDTO) throws IOException {
        if (file != null && !file.isEmpty()) {
            File dir = new File(uploadBasePath + File.separator + videoResPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID() + suffix;

            file.transferTo(new File(dir.getAbsolutePath() + File.separator + newFilename));
            videoResourcesDTO.setVideoUrl("/" + videoResPath + File.separator + newFilename);
        }
    }


}



